package com.lxp.tksys.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lxp.tksys.common.R;
import com.lxp.tksys.dto.DishDto;
import com.lxp.tksys.entity.Category;
import com.lxp.tksys.entity.Dish;
import com.lxp.tksys.entity.DishFlavor;
import com.lxp.tksys.service.CategoryService;
import com.lxp.tksys.service.DishFlavorService;
import com.lxp.tksys.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.websocket.server.PathParam;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping//新增菜品
    public R<String> save(@RequestBody DishDto dishDto){
        //log.info("新增菜品:{}",dishDto);
        dishService.saveWithFlavor(dishDto);             //自定义方法新增菜品-连带口味

        String key="dish_"+dishDto.getCategoryId()+"_"+"1";    //redis缓存
        redisTemplate.delete(key);

        return R.success("新增菜品成功");
    }

    //分页数据展示---------------------------Page有records属性，复制时要排除--------------
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize,String name){
        //log.info("page={},pageSize={}",page,pageSize);

        //分页构造器
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        Page<DishDto> pageInfo2 = new Page<>(page, pageSize);//拷贝从而显示dish没有的分类名称-口味

        //条件构造器根据sort排序
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.like(name!=null,Dish::getName,name);
        queryWrapper.orderByAsc(Dish::getCategoryId);
        //执行分页查询
        dishService.page(pageInfo,queryWrapper);                        //先根据dish的name查

        //对象拷贝
        BeanUtils.copyProperties(pageInfo,pageInfo2,"records");     //把dish的赋给dishdto除了records

        List<Dish> records = pageInfo.getRecords();             //原来page的records

        List<DishDto> list=records.stream().map((item)->{
            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(item,dishDto);//拷贝属性

            Long categoryId = item.getCategoryId(); //dish获取菜品分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);
            if(category!=null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);   //有了id查菜品分类的categoryName
            }

            return dishDto;
        }).collect(Collectors.toList());

        pageInfo2.setRecords(list);


        return R.success(pageInfo2);
    }

    //根据id查询菜品信息和口味,页面回显
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);  //查询时附带口味
        return R.success(dishDto);
    }

    @PutMapping//修改菜品--保存时候
    public R<String> update(@RequestBody DishDto dishDto){
        //log.info(dishDto.toString());
        dishService.updateWithFlavor(dishDto);              //更新时附带口味一起更新
        //全部清理
        //Set keys = redisTemplate.keys("dish_*");
        //redisTemplate.delete(keys);
        String key="dish_"+dishDto.getCategoryId()+"_"+"1";     //  redis缓存
        redisTemplate.delete(key);
        return R.success("修改菜品成功");
    }

    //菜品禁售
    @PostMapping("/status/{status}")
    public R<String> upStatus(@PathVariable("status") Integer status, @RequestParam List<Long> ids){
        //log.info("status:{}",status);
        //log.info("ids:{}",ids);
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.in(ids!=null,Dish::getId,ids);    //因为是ids集合，用in
        List<Dish> dishList = dishService.list(dishLambdaQueryWrapper);

        for (Dish dish : dishList) {         //如果dish存在则修改状态并update
            if(dish!=null){
                dish.setStatus(status);
                dishService.updateById(dish);
            }
        }
        return R.success("售卖状态修改成功！");
    }

    //菜品删除
    @DeleteMapping
    private R<String> delete(@RequestParam("ids") List<Long> ids){
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(ids!=null,Dish::getId,ids);
        List<Dish> dishList = dishService.list(queryWrapper);
        for (Dish dish : dishList) {
            if(dish!=null){
                dishService.removeById(dish);            //根据ids调用原始方法
            }
        }
        return R.success("删除成功！");
    }

    //根据条件查询菜品
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){     //返回值类型，除了拿dish还有口味，Dish->DishDto
        List<DishDto> dtoList=null;

        String key="dish_"+dish.getCategoryId()+"_"+dish.getStatus();
        //从redis中get获取缓存数据
        dtoList=(List<DishDto>) redisTemplate.opsForValue().get(key);
        //存在直接返回，不存在查询数据库并返回redis
        if(dtoList!=null){
            return  R.success(dtoList);
        }


        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        dishLambdaQueryWrapper.eq(Dish::getStatus,1);//起售状态才可以添加
        //排序条件
        dishLambdaQueryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(dishLambdaQueryWrapper);  //获取dish数据


        dtoList=list.stream().map((item)->{
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);     //拷贝dish数据到dishdto
            //根据菜品分类id查询对象
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if(category!=null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            Long dishId = item.getId();//菜品id
            LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId,dishId);
            List<DishFlavor> dishFlavorList = dishFlavorService.list(dishFlavorLambdaQueryWrapper);//根据菜品id获取口味
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());

        //不存在，缓存到redis
        redisTemplate.opsForValue().set(key,dtoList,60, TimeUnit.MINUTES);

        return R.success(dtoList);
    }


}
